define(function(require, exports, module) {
    'use strict';

    var rk = require('rk');
    require('./dialog/widget');

    $.widget('rk.xsyAccountHierarchy', $.rk.xsyAccountHierarchyDialog, {
        options: {},
        highlightClass: 'highlight',
        highlightColor: '#30dcf2',
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            // me._beIniting(rk.templateText(require('platform/widgets/crm/account/xsyAccountHierarchy/initing.tpl'), {}));
            elem.hide();

            elem.on('click', '.xsy_account_hierarchy_footer a', function() {
                rk.dialog({
                    title: rk.i18n('REFER_ACCOUNT_RELATION'),
                    width: $('body').width() * 0.7,
                    success: function(contentElem, footerElem) {
                        contentElem.xsyAccountHierarchyDialog({
                            data: me.fulldata //全数据展示
                        });
                    },
                    footer: false
                });
            });
            me.load();

            // 收听【外部】控件广播而来的事件
            me._listenOuterEvent('detailChanged', function(arg) {
                // arg.item: 编辑的字段
                if (arg.item.entryPropertyNameOnly == 'parentAccountId') {
                    me.load();
                }
            });

            me._listenOuterEvent('afterPopupEdit', function(arg) {
                me.load();
            });

        },
        load: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            //'/static/source/platform/manager/mock/hierarchy.json';
            //'/json/crm_account_detail/account_relations.action?id=245622'
            var data_url = '/json/crm_account_detail/account_relations.action';
            var relationsParameter = {};
            if (Number(me._getDetailId())) {
                relationsParameter = {
                    id: me._getDetailId()
                };
            } else {
                relationsParameter = {
                    gid: rk.crm.getGroupId()
                };
            }
            var jqxhr = $.getJSON(data_url, relationsParameter).done(function(json) {
                elem.html(rk.templateText(require('platform/widgets/crm/account/xsyAccountHierarchy/widget.tpl'), opt))
                if (!json.account[0].children || json.account[0].children.length == 0) {
                    // elem.hide();
                } else {
                    elem.show();
                }
                me.nodesMap = {};
                me.activeNode = null;
                json.account[0].viewtype = 'start';
                me.fulldata = me._processJson(json.account[0]);
                if (me.activeNode) me._markRoad(me.activeNode); //回朔之路

                //只展示二级数据
                // var partdata = {
                //     children: []
                // };
                // for(var k in me.fulldata){
                //     if(k != 'children') partdata[k] = me.fulldata[k];
                // };
                // for(var i=0,len=me.fulldata.children.length;i<len;i++){
                //     var child = me.fulldata.children[i];
                //     var partchild = {};
                //     for(var k in child){
                //         if(k != 'children') partchild[k] = child[k];
                //     }
                //     partdata.children.push(partchild);
                // }

                me._render(me.fulldata, function() {
                    elem.find('.xsy_account_hierarchy_body .canvas').css({
                        'overflow': 'hidden',
                        '-ms-overflow': 'hidden'
                    });
                });
            })
        },
        nodeTpl: require('platform/widgets/crm/account/xsyAccountHierarchy/node.tpl'),
        nodesMap: {},
        activeNode: null,
        _processJson: function(node) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var nodeId = node.id;

            if ((nodeId + '') == (me._getDetailId() + '') || (nodeId + '') == '99999999') {
                me.activeNode = node;
                node.viewtype = 'active';
            }
            me.nodesMap[nodeId] = node;

            if ($.isArray(node.children) && node.children.length > 0) {
                for (var i = 0, len = node.children.length; i < len; i++) {
                    var child = node.children[i];
                    child.parentId = nodeId;
                    me._processJson(node.children[i]);
                }
            } else {
                if (!node.viewtype) node.viewtype = 'leaf'
            }
            node.innerHTML = rk.templateText(me.nodeTpl, node);

            return node;
        },
        _markRoad: function(node) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            if (node.parentId) {
                var pnode = me.nodesMap[node.parentId];
                pnode.highlightClass = me.highlightClass;
                pnode.highlightColor = me.highlightColor;
                //TODO: 此处需要高亮通路连线，但第三方控件有个bug是分支也会被高亮，因此临时注掉
                // pnode.connectors = {
                //                         type: "step",
                //                         style: {
                //                             "stroke-width": 2,
                //                             "stroke": me.highlightColor
                //                         }
                //                     };
                pnode.innerHTML = rk.templateText(me.nodeTpl, pnode); //在此更新
                me._markRoad(pnode);
            }
        }
    });
});
